import ProForm, { ModalForm, DrawerForm, ProFormText, ProFormSelect, ProFormTextArea } from '@ant-design/pro-form';
import React, { useState, useRef } from 'react';

export function castType(castType, obj) {
    switch (castType) {
      case "int":
        return parseInt(obj)
      default:
        return obj
    }
  }

export function generateForm(columns, options = {
    defaultRow: null,
    disabled: [],
    formName: ''
  }) {
    const maxGroupFactor = 4
    const checkDisabled = col => ((options.disabled?.find(name => name == col.dataIndex)) ? true : false)
    const cols = columns.filter(col => !col.ignore).map(col => {
      if (col.valueEnum) {
        return [(
          <ProFormSelect
            key={`select_${options.formName}_${col.dataIndex}`}
            width="xs"
            options={(col.valueEnum && Object.keys(col.valueEnum).map(val => ({
              value: castType(col.castType, val),
              label: col.valueEnum[val].text
            })))}
            name={col.dataIndex}
            label={col.title}
            value={options.defaultRow?.()?.[col.dataIndex]}
            disabled={checkDisabled(col)}
            valueType={col.valueType}
          />
        ), 1]
      }
      return [(
        <ProFormText
          key={`formtext_${options.formName}_${col.dataIndex}`}
          width="md"
          name={col.dataIndex}
          label={col.title}
          value={options.defaultRow?.()?.[col.dataIndex]}
          disabled={checkDisabled(col)}
          valueType={col.valueType}
        />
      ), 2]
    }).reduce((arr, [elem, k]) => {
      if (arr.length == 0 || arr[arr.length - 1][1] >= maxGroupFactor) {
        arr.push([[], 0])
      }
      let last = arr[arr.length - 1]
      last[0].push(elem)
      last[1] += k
      return arr
    }, []).map((group, i) => ((
      <ProForm.Group key={`${i}`}>{group[0]}</ProForm.Group>
    )))
    return cols
  }